package com.project.wxServer.server.login.impl;

import com.project.common.core.domain.BaseServer;
import com.project.system.service.ISysUserService;
import com.project.wxServer.domain.pay.FaceToFace;
import com.project.wxServer.domain.pay.TOrderRecord;
import com.project.wxServer.domain.pay.WxPayInfo;
import com.project.wxServer.enums.CommodityType;
import com.project.wxServer.mapper.TOrderRecordMapper;
import com.project.wxServer.server.login.ITOrderRecordService;
import com.project.wxServer.server.pay.IPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 微信支付订单Service业务层处理
 *
 * @author project
 * @date 2021-07-10
 */
@Service
public class TOrderRecordServiceImpl extends BaseServer implements ITOrderRecordService {

    private static final Logger log = LoggerFactory.getLogger(TOrderRecordServiceImpl.class);

    @Resource
    private TOrderRecordMapper tOrderRecordMapper;

    @Autowired
    IPayService iPayService;

    @Autowired
    ISysUserService iSysUserService;

    /**
     * 查询微信支付订单
     *
     * @param commodityId 微信支付订单ID
     * @return 微信支付订单
     */
    @Override
    public TOrderRecord selectTOrderRecordById(String commodityId) {
        return tOrderRecordMapper.selectTOrderRecordById(commodityId);
    }

    /**
     * 查询微信支付订单列表
     *
     * @param tOrderRecord 微信支付订单
     * @return 微信支付订单
     */
    @Override
    public List<TOrderRecord> selectTOrderRecordList(TOrderRecord tOrderRecord) {
        return tOrderRecordMapper.selectTOrderRecordList(tOrderRecord);
    }

    /**
     * 新增微信支付订单
     *
     * @param tOrderRecord 微信支付订单
     * @return 结果
     */
    @Override
    public int insertTOrderRecord(TOrderRecord tOrderRecord) {
        super.insert(tOrderRecord);
        return tOrderRecordMapper.insertTOrderRecord(tOrderRecord);
    }

    /**
     * 修改微信支付订单
     *
     * @param tOrderRecord 微信支付订单
     * @return 结果
     */
    @Override
    public int updateTOrderRecord(TOrderRecord tOrderRecord) {
        super.update(tOrderRecord);
        return tOrderRecordMapper.updateTOrderRecord(tOrderRecord);
    }

    /**
     * 批量删除微信支付订单
     *
     * @param ids 需要删除的微信支付订单ID
     * @return 结果
     */
    @Override
    public int deleteTOrderRecordByIds(String[] ids) {
        return tOrderRecordMapper.deleteTOrderRecordByIds(ids);
    }

    /**
     * 删除微信支付订单信息
     *
     * @param id 微信支付订单ID
     * @return 结果
     */
    @Override
    public int deleteTOrderRecordById(String id) {
        return tOrderRecordMapper.deleteTOrderRecordById(id);
    }

    /**
     * 创建微信支付订单
     *
     * @param parame
     * @return
     */
    public TOrderRecord createWXOrder(Map<Object, Object> parame) {
        //查询校验是否重复订单
        String out_trade_no = parame.get("out_trade_no").toString();//商品订单编号
        String trade_type = parame.get("trade_type").toString();//支付方式
        WxPayInfo wxPayInfo = (WxPayInfo) parame.get("wx_pay_info");//订单信息
        FaceToFace faceToFace = (FaceToFace) parame.get("Face_To_Face");//面对面缴费
        //查询是否存在该订单
        TOrderRecord tOrderRecord = new TOrderRecord();
        if (tOrderRecordMapper.selectTOrderRecordById(out_trade_no) == null) {
            if (wxPayInfo != null) {
                //立即充值
                if (wxPayInfo.getPayType() == CommodityType.ON_PAYMENT.getValue()) {
                    //创建订单
                    tOrderRecord.setCommodityId(out_trade_no); //订单编号
                    tOrderRecord.setCommodityType(wxPayInfo.getPayType()); //订单类型
                    tOrderRecord.setUserId(wxPayInfo.getUserId()); //用户编号
                    tOrderRecord.setPaymentAmount(wxPayInfo.getPayAmount());//支付金额
                    tOrderRecord.setPaymentType(trade_type);//支付方式
                    tOrderRecord.setCommodityDescrible("微信支付-直接支付");//商品描述
                    tOrderRecord.setFailCause("取消支付");
                    tOrderRecord.setOrderStatus("0");//订单状态 0待支付
                    this.insertTOrderRecord(tOrderRecord);
                    log.info("{} - 微信支付-直接支付", out_trade_no);
                }
            }
        }
        return tOrderRecord;
    }

    /**
     * 修改订单状态
     *
     * @param result_code
     * @return
     */
    @Override
    public TOrderRecord updateWXOrder(String result_code, String trade_no) {
        //如果存在该订单
        TOrderRecord tOrderRecord = tOrderRecordMapper.selectTOrderRecordById(trade_no);
        if (!ObjectUtils.isEmpty(tOrderRecord)) {
            //1.表示已完成订单 2.表示未完成订单
            if (result_code.equalsIgnoreCase("1")) {
                tOrderRecord.setOrderStatus("1");
                tOrderRecord.setFailCause(" ");
            } else if (result_code.equalsIgnoreCase("0")) {
                tOrderRecord.setOrderStatus("2");
                tOrderRecord.setFailCause("订单" + trade_no + "支付失败");
            }
            this.updateTOrderRecord(tOrderRecord);
        }
        return tOrderRecord;
    }

    /**
     * 统计用户下余额
     *
     * @return
     */
    @Override
    @Transactional
    public BigDecimal countMoney(String userId) {
        BigDecimal balanceAmount = null;
        try {
            //缴费总额
            Integer payFeesAmount = tOrderRecordMapper.payFeesAmount(userId);
            //充值总额
            Integer rechargeAmount = tOrderRecordMapper.rechargeAmount(userId);
            if (rechargeAmount == null) {
                return new BigDecimal(0);
            } else {
                if (payFeesAmount == null) {
                    return new BigDecimal(rechargeAmount);
                }
                if (rechargeAmount.compareTo(payFeesAmount) == 1) {
                    balanceAmount = new BigDecimal(rechargeAmount).subtract(new BigDecimal(payFeesAmount));
                }
            }
        } catch (Exception e) {
            log.error("余额统计异常");
        }
        return balanceAmount;
    }
}
